<?php
/* 
 * Récupère les données du formulaire de méta et les injecte dans le workflow correspondant.
 */
require_once("../../config.php");
require_once("PlistParser.inc");
require_once("myLib.php");
global $CFG, $USER, $COURSE;
//Par défaut, succès
$success = 'SUCCESS';
$reason = "";

//Paramètres
$Ginstid = optional_param('instid', null, PARAM_INT);
$Gperform = optional_param('perform', null, PARAM_ALPHANUM);
$Gfilename = optional_param('filename', null, PARAM_ALPHANUM);
$Guuid = optional_param('cuuid', null, PARAM_SAFEDIR);
$Gcam = optional_param('cam', null, PARAM_ALPHAEXT);

if(!strrchr($CFG->podcast_path2tmpfiles, "/") || !strrchr($CFG->podcast_path2tmpfiles, '\\'))
    $path = $CFG->podcast_path2tmpfiles."/";

//On récupère les variables dynamiquement par rapport au workflow concerné (via l'uuid) et on construit
//le fichier XML correspondant
header('Content-Type: text/xml; charset=UTF-8');
$doc = new DOMDocument('1.0', 'utf-8');
$plist = $doc->createElement( "plist" );
$plist->setAttribute("version", "1.0");
$doc->appendChild( $plist );
$dict = $doc->createElement("dict");
$plist->appendChild( $dict );

if(is_allowed('mod/podcast:edit', $COURSE->id, $Ginstid)){
    $parser = new plistParser();
    $command1 = "ssh -i ".$CFG->podcast_path2rsakey." ".$CFG->podcast_username."@".$CFG->podcast_path2pcp." pcast --server ".$CFG->podcast_path2pcp." --user ".$CFG->podcast_username." --pass ".$CFG->podcast_password." --listworkflows";
    $output =  shell_exec($command1);
    $plister = $parser->parseRAW($output);
    foreach($plister["workflows"] as $wf) {
        if($wf['uuid'] == $_POST['uuid']){
            foreach($wf['user_requirements'] as $uri) {
                $post = $_POST[$uri];
                if(strcmp($uri, "Title") == 0){
                   $post = str_replace(" ", "_", $_POST[$uri]);
                }
                $xmlKey = $doc->createElement("key");
                $dict->appendChild($xmlKey);
                $xmlKey->appendChild($doc->createTextNode($uri));
                $xmlValue = $doc->createElement("string");
                $xmlValue->appendChild($doc->createTextNode($post));
                $dict->appendChild($xmlValue);
            }
            //On rajoute ici le login de l'utilisateur qui réalise l'upload dans le champ copyright.
            //Ceci a été fait de cette manière pour des raisons de simplicité, libre à vous de rajouter
            //une méta pour le login.
            //Le délimiteur est "_"
            $xmlKey = $doc->createElement("key");
            $dict->appendChild($xmlKey);
            $xmlKey->appendChild($doc->createTextNode("Copyright"));
            $xmlValue = $doc->createElement("string");
            $xmlValue->appendChild($doc->createTextNode($USER->username."_Copyright (c) 2009 Universite NANCY 2"));
            $dict->appendChild($xmlValue);

            $wfname = $wf['name'];
        }
    }

    //Vieux Hack du doctype...
    $doc->formatOutput = true;
    $doc->preserveWhiteSpace = false;
    $tmpOut = $doc->saveXML();
    $doctype='
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    ';
    $tmpOut = preg_replace('/\n/',$doctype,$tmpOut,1);
    $tmpOut = stripslashes($tmpOut);
    $tmpOut = str_replace("'","&quot;",$tmpOut);
    $tmpOut = str_replace('"',"&quot;",$tmpOut);

    //On écrit ce fichier sur le serveur moodle
    $fichierLocal = fopen($CFG->dataroot.'/tmpXmlMeta'.$USER->id.'_'.$_POST['uuid'].'.plist', 'w');
    fputs($fichierLocal,$tmpOut);
    fclose($fichierLocal);

    //On upload le fichier de métas sur le serveur Apple
    $commandUP = "scp -i ".$CFG->podcast_path2rsakey." ".$CFG->dataroot."/tmpXmlMeta".$USER->id."_".$_POST['uuid'].".plist ".$CFG->podcast_username."@".$CFG->podcast_path2pcp.":".$path."/tmpXmlMeta".$USER->id."_".$_POST['uuid'].'.plist';
    $response =  exec($commandUP, $output, $return);
    if($return == 0){
        //On lance la commande stop
        if(isset($Gperform) && (strcmp($Gperform, 'camera') == 0)){
            $command = "ssh -i ".$CFG->podcast_path2rsakey." ".$CFG->podcast_username."@".$CFG->podcast_path2pcp." pcast --server ".$CFG->podcast_path2pcp." --user ".$CFG->podcast_username." --pass ".$CFG->podcast_password." --stop \\'".$_POST['camera']."\\' --metadata ".$path."tmpXmlMeta".$USER->id."_".$_POST['uuid'].".plist --workflow \"".$wfname."\"";
        }elseif(isset($Gperform) && (strcmp($Gperform, 'upload') == 0)){
            $command = "ssh -i ".$CFG->podcast_path2rsakey." ".$CFG->podcast_username."@".$CFG->podcast_path2pcp." pcast --server ".$CFG->podcast_path2pcp." --user ".$CFG->podcast_username." --pass ".$CFG->podcast_password." --submit --file ".$path.$_GET['filename']." --metadata ".$path."tmpXmlMeta".$USER->id."_".$_POST['uuid'].".plist --workflow \"".$wfname."\"";
        }
        $return = 0;
        $response =  exec($command, $output, $return);
        if($return != 0){
            $success = "FATAL";
            $reason = "Failes to perform : ".getError($return);
        }else{
            //On détruit les fichiers temporaires créés sur le serveur apple
            $commandDELETE = "ssh -i ".$CFG->podcast_path2rsakey." ".$CFG->podcast_username."@".$CFG->podcast_path2pcp." rm ".$path."tmpXmlMeta".$USER->id."_".$_POST['uuid'].".plist";
            $return = 0;
            $response =  exec($commandDELETE, $output, $return);
            if($return != 0){
                $success = "WARNING";
                $reason = "Could not delete metadata file on Podcast server.";
            }

            if(isset($Gperform) && (strcmp($Gperform, 'upload') == 0)){
                $commandDELETE = "ssh -i ".$CFG->podcast_path2rsakey." ".$CFG->podcast_username."@".$CFG->podcast_path2pcp." rm ".$path.$Gfilename;
                $return = 0;
                $response =  exec($commandDELETE, $output, $return);
                if($return != 0){
                    $success = "WARNING";
                    $reason = "Could not delete source file on Podcast server.";
                }
            }
        }
        unlink($CFG->dataroot.'/tmpXmlMeta'.$USER->id.'_'.$_POST['uuid'].'.plist');
    }else{
        $success = "FATAL";
        $reason = "Metadata file failed to upload. Check your settings in admin section.";
    }

    //On dévérouille la caméra
    if((($success === "SUCCESS") || ($success === "WARNING")) && (strcmp($Gperform, 'upload') != 0)){
        if(delete_records("podcast_cameras", "uuid", strval($Guuid), "user", strval($USER->id))){
                //On laisse $success à sa valeur.
            }else{
                $success = "FAILURE";
                $reason = "Podcast submission is OK. But failed to unlock the cam. Try to cancel.";
            }
    }

}else{
    $success = "FAILURE";
    $reason = "Permission denied.";
}

//On détruit les fichiers temporaires créés sur le serveur moodle

//On rend compte au client du succès ou de l'échec de l'opération.
$doc = new DOMDocument('1.0', 'utf-8');
$message = $doc->createElement( "message" );
$doc->appendChild( $message );
$xmlRespSucc = $doc->createElement( "Success" );
$xmlRespSuccWhy = $doc->createElement( "Reason" );
$xmlRespCameraName = $doc->createElement( "cameraName" );
$xmlRespCameraUuid = $doc->createElement( "cameraUuid" );
$xmlRespCameraName->appendChild( $doc->createTextNode( $Gcam ));
$xmlRespCameraUuid->appendChild( $doc->createTextNode( $Guuid ));
$xmlRespSucc->appendChild( $doc->createTextNode( $success ));
$xmlRespSuccWhy->appendChild( $doc->createTextNode( $reason ));
$message->appendChild( $xmlRespSucc );
$message->appendChild( $xmlRespSuccWhy );
$message->appendChild( $xmlRespCameraName );
$message->appendChild( $xmlRespCameraUuid );
echo $doc->saveXML();
?>